package Homework6;

public class BinaryToDecimal {
    public static int binaryToDecimal(String binary) throws BinaryFormatException {
        // 检查字符串是否为有效的二进制字符串
        if (binary == null || binary.isEmpty()) {
            throw new BinaryFormatException("Binary string cannot be empty or null");
        }

        for (char c : binary.toCharArray()) {
            if (c != '0' && c != '1') {
                throw new BinaryFormatException("Binary string contain symbols other than 0 and 1.");
            }
        }

        // 将二进制字符串转换为十进制整数
        int decimal = 0;
        for (int i = 0; i < binary.length(); i++) {
            char bit = binary.charAt(i);
            decimal = decimal * 2 + (bit - '0');
        }

        return decimal;
    }
}
